import config from '@/config/config.js';
import {getToken,setToken,getCookie,setCookie} from '@/utils/auth';
import tool from '@/utils/common.js';
let timeout = 10000;
const baseUrl = config.baseUrl;
const request = config => {
	const isToken = config?.headers?.isToken||false;
	const isSystemLogin=config.headers.isSystemLogin;
	config.header = config.header || {};
	// isSystemLogin?config.header['Content-Type'] = 'application/json':config.header['Content-Type'] = 'application/x-www-form-urlencoded';
	config.header['Content-Type'] = 'application/json';
	// if(getToken() && isToken) {config.header['Authorization'] = uni.getStorageSync('token_type')+' ' + uni.getStorageSync('token')};
	if(getToken() && isToken) {config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')};
	if (config.params) {
		let url = config.url + '?' + tool.tansParams(config.params)
		config.url = url.slice(0, -1)
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json',
			success(res) {
				if(res.cookies&&res.cookies.length>0){
					console.log("总请求数据",res);
					setCookie(res.cookies[0])
				}
				let {code,data,msg}=res.data;
				switch (code) {
					case 403:
						tool.toastTip(msg||'无效的会话，或者会话已过期，请重新登录。','none',1500);
						setTimeout(()=>{
							uni.navigateTo({
								url:'/pagesMine/login'
							})
						},1500)
						break;
					default:
						break;
				}
				resolve(res.data)
			},
			fail: (error) => {
				let {errMsg} = error
				if (errMsg === 'Network Error') {
					errMsg = '后端接口连接异常'
				} else if (errMsg.includes('timeout')) {
					errMsg = '系统接口请求超时'
				} else if (errMsg.includes('Request failed with status code')) {
					errMsg = '系统接口' + errMsg.substr(errMsg.length - 3) + '异常'
				}
				reject(error)
			},
			complete() {}
		})
	})
}
export default request